package net.flydy.ywxcx.wxcloudrun.common;

import lombok.NonNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author flydy
 */

public class MyByteArrayMultipartFile implements MultipartFile {

    String name;

    String originalFilename;

    String contentType;

    public MyByteArrayMultipartFile(byte[] buff, String name, String originalFilename, String contentType) {
        bytes = buff;
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
    }

    @NonNull
    byte[] bytes;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return bytes.length == 0;
    }

    @Override
    public long getSize() {
        return bytes.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return bytes;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(bytes);
    }

    @Override
    public void transferTo(File destination) throws IOException {
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(destination);
            outputStream.write(bytes);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

}
